package com.glb.gilibuy.service.impl;

import com.glb.gilibuy.dao.UserDao;
import com.glb.gilibuy.entity.User;
import com.glb.gilibuy.entity.UserExample;
import com.glb.gilibuy.service.UserService;
import com.glb.gilibuy.util.BeanUtil;
import com.glb.gilibuy.util.MD5Util;
import com.glb.gilibuy.util.MapGenerator;
import com.glb.gilibuy.util.SnowflakeIdUtil;
import com.glb.gilibuy.web.vo.UserVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @Description:
 * @Author: Yingtian qian
 * @Date: 2021/8/2 11:31
 */
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserDao userDao;

    @Override
    public Map<String, Object> registerUser(String username, String password, String identity, boolean isPhone) {
        UserExample example = new UserExample();
        example.or().andUsernameEqualTo(username);
        List<User> userList = userDao.selectByExample(example);
        if (!userList.isEmpty()) {
            return MapGenerator.getRes(509, "用户名已被注册！");
        }
        if (isPhone) {
            UserExample example2 = new UserExample();
            example2.or().andPhoneEqualTo(identity);
            List<User> userList2 = userDao.selectByExample(example2);
            if (!userList2.isEmpty()) {
                return MapGenerator.getRes(510, "手机号已被注册！");
            }
        } else {
            UserExample example2 = new UserExample();
            example2.or().andEmailEqualTo(identity);
            List<User> userList2 = userDao.selectByExample(example2);
            if (!userList2.isEmpty()) {
                return MapGenerator.getRes(511, "邮箱已被注册！");
            }
        }

        User user = new User();
        user.setUsername(username);
        //密码用MD5方式加密存入user
        user.setPassword(MD5Util.md5Encode(password));
        user.setAvatar("/images/noface.jpg");
        user.setGender(0);
        user.setIsLocked(0);
        if (isPhone) {
            user.setPhone(identity);
        } else {
            user.setEmail(identity);
        }
        user.setUserId(SnowflakeIdUtil.getSnowflakeId() + "");
        user.setGmtCreate(new Date());

        if (userDao.insertSelective(user) > 0) {
            //注册成功
            return MapGenerator.getRes(200, "注册成功！");
        }
        //注册失败，内部错误
        return MapGenerator.getRes(520, "内部错误！");
    }

    @Override
    public Map<String, Object> checkLogin(String username, String password, HttpSession httpSession) {
        UserExample example = new UserExample();
        example.or().andUsernameEqualTo(username).andPasswordEqualTo(password);
        List<User> userList = userDao.selectByExample(example);

        if (!userList.isEmpty() && httpSession != null) {
            User user = userList.get(0);
            if (user.getIsLocked() == 1) {
                return MapGenerator.getRes(502, "该用户已被封禁！");
            }

            //用户名大于7缩写，可选功能
            if (user.getUsername() != null && user.getUsername().length() > 7) {
                String tempName = user.getUsername().substring(0, 7) + "..";
                user.setUsername(tempName);
            }

            UserVO userVO = new UserVO();
            BeanUtil.copyOne(user, userVO);
            httpSession.setAttribute("user", userVO);
            System.out.println("登录用户:" + httpSession.toString());
            //return MapGenerator.getRes(200,"登录成功！");
            return MapGenerator.getResWithData(200, "登录成功！", userVO);
        }
        return MapGenerator.getRes(500, "用户名或密码错误！");
    }

    @Override
    public Map<String, Object> updateUserPassword(User user) {
        UserExample example = new UserExample();
        //检查用户是否存在
        if (user.getPhone() != null) {
            example.or().andPhoneEqualTo(user.getPhone());
        } else {
            example.or().andEmailEqualTo(user.getEmail());
        }
        List<User> userList = userDao.selectByExample(example);
        if (userList.isEmpty()) {
            return MapGenerator.getRes(504, "用户不存在！");
        }

        User userFromDB = userList.get(0);
        if (userFromDB.getIsLocked() == 1) {
            return MapGenerator.getRes(505, "该用户已被封禁！");
        }
        //密码用MD5方式加密存入user
        userFromDB.setPassword(MD5Util.md5Encode(user.getPassword()));

        if (userDao.updateByExampleSelective(userFromDB, example) > 0) {
            //修改密码成功
            return MapGenerator.getRes(200, "修改密码成功！");
        }
        //修改失败，内部错误
        return MapGenerator.getRes(520, "内部错误！");
    }

    @Override
    public UserVO updateUserInfo(UserVO userVO, HttpSession httpSession) {
        //前端输入的userVO，有效信息只包括：生日/性别/头像地址/手机号/邮箱
        //从session中拿的userVO，只要其中的userId（必须登录后才能拿）
        UserVO userTemp = (UserVO) httpSession.getAttribute("user");
        //用userId从数据库里拿userEntity
        UserExample example = new UserExample();
        example.or().andUserIdEqualTo(userTemp.getUserId());
        User userFromDB = userDao.selectByExample(example).get(0);
        //如果查到对应的userEntity
        if (userFromDB != null) {
            //用前端输入的userVO修改userEntity
            if (!StringUtils.isEmpty(userVO.getBirthday())) {
                userFromDB.setBirthday(userVO.getBirthday());
            }
            if (!StringUtils.isEmpty(userVO.getGender())) {
                userFromDB.setGender(userVO.getGender());
            }
            if (!StringUtils.isEmpty(userVO.getAvatar())) {
                userFromDB.setAvatar(userVO.getAvatar());
            }
            if (!StringUtils.isEmpty(userVO.getPhone())) {
                UserExample example2 = new UserExample();
                example2.or().andPhoneEqualTo(userVO.getPhone());
                List<User> userList2 = userDao.selectByExample(example2);
                if (!userList2.isEmpty()) {
                    return null;
                }
                userFromDB.setPhone(userVO.getPhone());
            }
            if (!StringUtils.isEmpty(userVO.getEmail())) {
                UserExample example2 = new UserExample();
                example2.or().andEmailEqualTo(userVO.getEmail());
                List<User> userList2 = userDao.selectByExample(example2);
                if (!userList2.isEmpty()) {
                    return null;
                }
                userFromDB.setEmail(userVO.getEmail());
            }
            // 用userEntity更新用户
            if (userDao.updateByPrimaryKeySelective(userFromDB) > 0) {
                //如果更新成功，重新拿userEntity，根据其更新session中的userVO
                UserVO userVO2 = new UserVO();
                userFromDB = userDao.selectByPrimaryKey(userFromDB.getId());
                BeanUtil.copyOne(userFromDB, userVO2);
                httpSession.setAttribute("user", userVO2);
                return userVO2;
            }
        }
        //更新失败
        return null;
    }

    @Override
    public Boolean isIdentityExist(String identity, boolean isPhone, HttpSession httpSession) {
        UserVO userTemp = (UserVO) httpSession.getAttribute("user");
        //用userId从数据库里拿userEntity
        UserExample example = new UserExample();
        example.or().andUserIdEqualTo(userTemp.getUserId());
        User userFromDB = userDao.selectByExample(example).get(0);
        if (userFromDB != null) {
            if (isPhone) {
                return userFromDB.getPhone().equals(identity);
            } else {
                return userFromDB.getEmail().equals(identity);
            }
        }
        return false;
    }

    @Override
    public Boolean lockUsers(String[] ids, int status) {
        return null;
    }

    @Override
    public List<User> findAllUsers() {
        return null;
    }
}
